import requests
import json

def get_access_token():
    CLIENT_ID1 = 'YrnG3qP8oaFLB9YQvXFcW7eL'
    CLIENT_SECRET1 = 'rp0Ad1QDHGOU5HyA2TARvfphLUlszmza'
    CLIENT_ID2 = 'bce-v3/ALTAK-zTAdXmWSN0tYor8qTrcHy/709ed71a0df7d1b9da0a71aa9ea614e57b8f28bc'
    CLIENT_SECRET2 = 'fc50463c3782467f9b33ccce962ddaae'
    CLIENT_ID = '6XUa10kSl6lDCokWvACoWeKL'
    CLIENT_SECRET = '2Cef6J4fVjG4lKwjoSk1hTC1T1DTrkCT'
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={CLIENT_ID1}&client_secret={CLIENT_SECRET1}"
    
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=json.dumps(""))
    return response.json().get("access_token")

def chat(content):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + get_access_token()
    
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": content
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    result = response.json()
    print("AI API响应:", result)  # 添加调试日志

     # 1. 如果 result 本身就是字符串
    if isinstance(result, str):
        return result

    # 2. 取出 result["result"]
    r = result.get("result")
    if isinstance(r, str):
        return r
    elif isinstance(r, dict):
        return r.get("content", "")

    # 3. 如果出现 error_code
    if result.get("error_code"):
        raise Exception(result.get("error_msg", "未知错误"))

    # 4. 兜底
    return "AI暂时无法回复"